from rest_framework import viewsets
from rest_framework.response import Response

from manage.authentication import JWTAuth
from manage.models.system import Menu
from manage.permission import CustomPermission
from manage.serializers.system import MenuSerializer


class MenuViewSet(viewsets.ModelViewSet):
    queryset = Menu.objects.all()
    serializer_class = MenuSerializer
    # 使用自定义登录认证类验证登录状态
    authentication_classes = (JWTAuth,)
    # 使用自定义权限验证类进行权限验证
    permission_classes = [CustomPermission]
    # 禁用分页功能
    pagination_class = None
    # 设置权限代码
    rbac_permissions = {
        'list': 'menu:list',
        'retrieve': 'menu:detail',
        'create': 'menu:create',
        'update': 'menu:update',
        'partial_update': 'menu:update',
        'destroy': 'menu.destroy'
    }

    def list(self, request, *args, **kwargs):
        # 重写 list 不会影响 permission_classes、filter_backends 等，
        # 因为 self.filter_queryset() 和权限检查是在父类方法中自动处理的（但你手动调用 filter_queryset 就能继承这些行为）
        queryset = self.filter_queryset(Menu.objects.filter(parent_id__isnull=True).all())
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
